package com.hbt.english.service.impl;

import com.hbt.api.entity.CommonResult;
import com.hbt.api.entity.User;
import com.hbt.api.utils.FakeRedis;
import com.hbt.english.dao.UserMapper;
import com.hbt.english.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
//@Cacheable(cacheNames = {"user"}, key = "#username")
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisTemplate<String, String> redisTemplate;
//    @Value("${img_path}")
    String img_path;

    public CommonResult getUserByToken(String token){
//        String username = redisTemplate.opsForValue().get(token);
        String username = FakeRedis.getUsernameByToken(token);
        User user = userMapper.getUserByUsername(username);
        return new CommonResult<User>(1, "getUserByUsername 获取user", user);
    }

    public CommonResult uploadAvatar(MultipartFile file, String token) throws IOException {
        if (file!=null){
            System.out.println("file !=null");
            System.out.println("文件名"+file.getOriginalFilename());
        }else{
            System.out.println("file == null");
        }
        if (token!=null){
            System.out.println("token !=null:"+token);
        }else{
            System.out.println("token == null");
        }
        //正文开始
        //通过token到redis获取username信息
        CommonResult<User> commonResult = getUserByToken(token);
        User user = commonResult.getT();
        //通过随机uuid获取新的图片名
        String file_name = file.getOriginalFilename();
        String old_img_name = user.getAvatar();
        System.out.println("old img_name:"+old_img_name);
        String houz = file_name.substring(file_name.lastIndexOf("."));
        String img_new_name = UUID.randomUUID().toString()+houz;
        System.out.println("new img_name:"+img_new_name);
        //通过username设置mysql里面对应uuid图片名数据的avatar
        user.setAvatar(img_new_name);
        userMapper.updateAvatarByUsername(user);
        System.out.println("mysql 的 avatar 成功更新");
        //通过file.transform方法将图片设置到对应文件夹位置
        File new_file = new File(img_path+"/"+img_new_name);
        System.out.println("图片路径："+img_path+"/"+img_new_name);
        file.transferTo(new_file);
        System.out.println("图片上传成功");
        //将旧的头像图片删除.除了default_avatar.jpg
        if(!user.getAvatar().equals("default_avatar.jpg")){
            String delete_img_url = img_path+"/"+old_img_name;
            File f_delete = new File(delete_img_url);
            f_delete.delete();
            System.out.println("图片删除成功:"+delete_img_url);
        }
        CommonResult result = new CommonResult<String>();
        result.setCode(200);
        result.setMsg("修改头像成功");
        result.setT(img_new_name);
        System.out.println("修改头像成功");
        return result;
    }//uploadAvatar method end

    public CommonResult dologin(User user) {
        //判断是否username和password为空
        if (user.getUsername().equals("")||user.getPassword().equals("")){
            return new CommonResult<User>(0, "账号或密码不能为空");
        }else {
            //去数据库查找对比username和password
            User user1 = userMapper.getUserByUsernameAndPassword(user);
            if (user1!=null){
                String uuid = UUID.randomUUID().toString();
                //将token设置到redis中，该token保存有username
//                redisTemplate.opsForValue().set(uuid, user1.getUsername());
//                redisTemplate.expire(uuid, 9000, TimeUnit.SECONDS);
                return new CommonResult<String>(1, "登录成功:"+user.getUsername(), uuid);
            }else {
                return new CommonResult<User>(0, "账号或密码错误:"+user.getUsername(), user);
            }

        }
    }


}
